/*
 * @Description:角色server
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-19 14:47:34
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-09 17:57:42
 */
const execSQL = require('../db/connect')
const { createWhereSql } = require('../utils/sql')
const { guid } = require('../utils/index')
var _ = require('lodash')
async function roleServer(rid) {
  const tsql = `select * from dy_tmenu`
  let result = []
  const tData = await execSQL(tsql)
  if (tData.length > 0) {
    result = tData.reduce((cur, next) => {
      if (!next.mid) {
        next.mid = ''
      }
      const mIdArr = next.mid.split(',')
      if (mIdArr.length > 0 && mIdArr.includes(`${rid}`)) {
        cur.push(next)
      }
      return cur
    }, [])
  }
  return result
}
// 更新语句
function updateSql(targetTable, data, target = 'id') {
  let str = ''
  const keys = Object.keys(data)
  for (let i = 0; i < keys.length; i++) {
    const targetKey = keys[i]
    if (targetKey !== target) {
      str += `${targetKey}= '${data[targetKey] ? data[targetKey] : ''}',`
    }
  }
  const resultStr = str.substring(0, str.length - 1)
  const sql = `UPDATE ${targetTable} SET ${resultStr} WHERE ${target} = '${data[target]}';`
  return sql
}
function createInsertSql(targetTable, data) {
  const sql = `INSERT INTO ${targetTable} `
  const keys = Object.keys(data)
  let keysStr = ''
  let valueStr = ''
  for (let i = 0; i < keys.length; i++) {
    const targer = keys[i]
    const spilt = `${i === keys.length - 1 ? '' : ','}`
    keysStr += `${targer}${spilt}`
    valueStr += `'${data[targer]}'${spilt}`
  }
  const resultSql = `${sql}(${keysStr}) VALUES (${valueStr})`
  return resultSql
}
async function updateRoleServer(res) {
  if (res.id) {
    await handleMenuData(res) // 处理菜单数据
    delete res.mid
    const sql = updateSql('dy_role', res)
    console.log(sql, 'sql')
    const result = await execSQL(sql)
    handleUserData(res) // 更新用户数据
    return result
  } else { // 新增
    if (!res.userId) {
      res.userId = []
    }
    res.userId = res.userId.join(',')
    const rid = guid()
    res.rid = rid
    const addData = _.cloneDeep(res)
    delete addData.mid
    console.log(addData, 'addData')
    const sql = createInsertSql('dy_role', addData)
    await execSQL(sql)
    handleAddMenuId(res)
    handleUserData(res)
    console.log(sql, 'sql')
  }
}
async function handleAddMenuId(res) {
  handleMenuData(res)
}
async function handleMenuData(res) {
  const targetTable = 'dy_tmenu'
  const selectMenuData = await execSQL(`select * from ${targetTable}`)
  const sourceMid = res.mid.map(v => `${v.id}`)
  for (let i = 0; i < selectMenuData.length; i++) {
    const target = selectMenuData[i]
    const hasMid = target.mid.split(',').map(v => `${v}`).filter(v => v !== `${res.rid}`)
    if (sourceMid.includes(`${target.id}`)) {
      hasMid.push(res.rid)
    }
    const sql = updateSql(targetTable, { mid: hasMid.join(','), id: selectMenuData[i].id })
    await execSQL(sql)
  }
}
async function handleUserData(res) {
  const targetTable = 'dy_user'
  const selectUserData = await execSQL(`select * from ${targetTable}`)
  const targetUserId = res.userId
  const filterUserData = selectUserData.filter(v => targetUserId.includes(v.userId))
  const oldRidData = selectUserData.filter(v => v.rid === res.rid)
  if (oldRidData.length > 0) {
    for (let i = 0; i < oldRidData.length; i++) {
      const sql = updateSql(targetTable, { rid: '0', id: oldRidData[i].id })
      await execSQL(sql)
    }
  }
  if (filterUserData.length > 0) {
    for (let i = 0; i < filterUserData.length; i++) {
      const sql = updateSql(targetTable, { rid: res.rid, id: filterUserData[i].id })
      await execSQL(sql)
    }
  }
}

// 查询所有角色
async function findRoleServer(params) {
  let sql = ''
  let result = []
  if (!params) {
    sql = createWhereSql('dy_role')
  } else {
    const { rName, rdesc, rStatus } = params
    const sqlParams = {
      rName,
      rdesc,
      rStatus
    }
    const like = ['rName', 'rdesc']
    sql = createWhereSql('dy_role', sqlParams, like)
    const roleData = await execSQL(sql)
    result = await handleRoleData(roleData)
    console.log(result, 'result')
    return result
  }
  result = await execSQL(sql)
  return result
}

async function handleRoleData(data) {
  const tsql = `select * from dy_tmenu`
  const tData = await execSQL(tsql)
  const menuData = tData.reduce((cur, next) => {
    const targetKey = next.mid.split(',')
    if (targetKey.length > 0) {
      targetKey.forEach(v => {
        if (!cur[v]) {
          cur[v] = []
        }
        cur[v].push(next)
      })
    } else {
      if (!cur[next.mid]) {
        cur[next.mid] = []
      }
      cur[next.mid].push(next)
    }
    return cur
  }, {})
  data.forEach(v => {
    v.mid = menuData[v.rid]
  })
  return data
}

module.exports = {
  roleServer,
  findRoleServer,
  updateRoleServer
}
